<template>
  <el-dialog
    :before-close="close" :close-on-click-modal="false" :visible.sync="dialogVisible" title="权限申请" width="80%"
    :append-to-body="true" @opened="open"
  >
    <el-form ref="submitForm" :model="submitForm">
      <el-form-item :rules="[{required: true, message: '请输入标题', trigger: 'blur'}]" label="标题" prop="title">
        <el-input v-model="submitForm.title" placeholder="请输入标题"/>
      </el-form-item>
      <el-form-item
        :rules="[{required: true, message: '请输入申请说明', trigger: 'blur'}]" label="申请说明"
        prop="applyRemark"
      >
        <el-input v-model="submitForm.applyRemark" placeholder="请输入申请说明" type="textarea"/>
      </el-form-item>

      <!-- 申请信息 -->
      <div v-if="submitForm" :key="submitForm.id">
        <el-divider content-position="left">
          申请信息
        </el-divider>
        <el-card
          v-for="(authInfo, index) in submitForm.authInfos" :key="index" class="box-card"
          style="margin-bottom: 20px"
        >
          <div slot="header">
            <span style="vertical-align: middle">
              申请信息{{ index + 1 }}
            </span>
            <span style="float: right; padding: 3px 0; vertical-align: middle">
              <el-button type="text" @click="addAuthInfo(index)">复制</el-button>
              <el-button
                v-if="submitForm.authInfos.length>1" type="text"
                @click="deleteAuthInfo(index)"
              >删除</el-button>
              <el-button
                v-if="!submitForm.authInfos[index].show" type="text"
                @click="submitForm.authInfos[index].show=true"
              >展开</el-button>
              <el-button v-else type="text" @click="submitForm.authInfos[index].show=false">收起</el-button>
            </span>
            <span/>
          </div>
          <apply-auth-info-div
            v-show="submitForm.authInfos[index].show!==false" v-model="submitForm.authInfos[index]"
            :mode="mode"
          />
        </el-card>
      </div>
    </el-form>
    <div>
      <el-button style="float: right" type="primary" :disabled="applyButtonDisabled" @click="apply"> 提 交</el-button>
      <div style="clear:both"/>
    </div>
  </el-dialog>
</template>
<script>
import {apply, detail, listApproveUser} from "@/api/auth/auth";
import ApplyAuthInfoDiv from "@/views/auth/apply/applyAuthInfoDiv";
import {list as authInfoResourceList} from "@/api/auth/authInfoResource";
import {list as authInfoList} from "@/api/auth/authInfo";

export default {
  name: "ApplyDialog",
  components: {
    ApplyAuthInfoDiv,
  },
  props: {
    authId: {type: Number, default: null},
    authInfoId: {type: Number, default: null},
    authInfoResourceId: {type: Number, default: null},
    mode: {type: String, default: 'NORMAL'},
    dialogVisible: {type: Boolean, default: false},
    isRenewal: {type: Boolean, default: false}
  },

  data() {
    return {
      submitForm: this.resetInfo(),
      approveUsers: [],
      accesses: [],
      applyButtonDisabled: false,
      defaultUseUser: null,
    }
  },

  methods: {
    addAuthInfo(index) {
      let copies = JSON.parse(JSON.stringify(this.submitForm.authInfos))
      this.$set(this.submitForm, 'authInfos', [])
      this.$nextTick(() => {
        copies.splice(index, 0, JSON.parse(JSON.stringify(copies[index])))
        this.$set(this.submitForm, 'authInfos', copies)
      })
    },

    deleteAuthInfo(index) {
      let copies = JSON.parse(JSON.stringify(this.submitForm.authInfos))
      this.$set(this.submitForm, 'authInfos', [])
      this.$nextTick(() => {
        copies.splice(index, 1)
        this.$set(this.submitForm, 'authInfos', copies)
      })
    },

    error(msg) {
      return new Error(msg)
    },

    resetInfo() {
      return {
        title: sessionStorage.getItem("bdpUserCn") + " 权限申请",
        mode: this.mode,
        authInfos: [this.resetAuthInfo()]
      }
    },

    resetAuthInfo() {
      return {
        startTime: new Date(),
        authService: null,
        authType: null,
        ips: [],
        accesses: [],
        userType: null,
        usernames: [],
        useUsers: [],
        show: true,
        authInfoResources: []
      }
    },
    /**
     * 打开本Dialog时初始化操作
     */
    open() {
      // 复制其他的权限申请
      if (this.authId) {
        detail(this.authId).then(res => {
          let data = res.data

          // 去除ID
          // data.id = undefined

          // 去除申请信息
          data.applyUser = undefined
          data.applyTime = undefined

          let authInfos = []
          let authInfoResourceMap = {}

          authInfoResourceList({authId: this.authId}).then(res => {
            res.data.forEach(ele => {
              let value = authInfoResourceMap[ele.authInfoId]
              if (!value) {
                value = []
              }
              value.push(ele)
              authInfoResourceMap[ele.authInfoId] = value
            })

            authInfoList({authId: this.authId}).then(res => {
              authInfos = res.data

              data.authInfos = []
              authInfos.forEach(authInfo => {
                if (this.authInfoId && authInfo.id !== this.authInfoId) {
                  return
                }
                // 复制时，去除presto显示
                if (authInfo.authService === "PRESTO"){
                  return
                }

                // 修改开始时间和结束时间
                authInfo.startTime = new Date()
                authInfo.endTime = new Date(authInfo.startTime.getTime() + 90 * 24 * 3600 * 1000)

                // 增加show属性
                authInfo.show = true

                // 增加resource show 属性
                const authInfoResources = authInfoResourceMap[authInfo.id]
                authInfo.authInfoResources = []
                authInfoResources.forEach(authInfoResource => {
                  if (this.authInfoResourceId && authInfoResource.id !== this.authInfoResourceId) {
                    return
                  }
                  authInfoResource.show = true
                  authInfo.authInfoResources.push(authInfoResource)
                })

                data.authInfos.push(authInfo)
              })

              this.submitForm = data
            })
          })
        })
      } else {
        this.submitForm = this.resetInfo()
      }
      listApproveUser().then(res => {
        this.approveUsers = res.data
      })
    },

    /**
     * 关闭本Dialog
     */
    close() {
      this.$refs.submitForm.clearValidate()
      this.submitForm = this.resetInfo()
      this.$parent.applyDialogVisible = false
      this.$parent.page()
    },

    /**
     * 提交申请
     */
    apply() {
      this.applyButtonDisabled = true
      this.$refs.submitForm.validate(valid => {
        if (valid) {
          // 构建authApprove
          this.submitForm.authApproves = []
          this.approveUsers.forEach(approveUser => {
            this.submitForm.authApproves.push({approveUser: approveUser})
          })

          // 去除authInfo show参数
          if (this.submitForm.authInfos) {
            this.submitForm.authInfos.forEach(authInfo => {
              authInfo.id = undefined
              authInfo.authId = undefined
              authInfo.show = undefined
              // 去除info show参数
              if (authInfo && authInfo.authInfoResources) {
                authInfo.authInfoResources.forEach(resource => {
                  resource.id = undefined
                  resource.show = undefined
                })
              }
            })
          }

          apply(this.authInfoId, JSON.parse(JSON.stringify(this.submitForm))).then(() => {
            this.$message({message: "权限申请成功", type: "success"})
            this.close()
            this.applyButtonDisabled = false
          })
        } else {
          this.applyButtonDisabled = false
        }
      })
    }
  }
}
</script>

<style lang="scss">
</style>
